//
//  AppTools.m
//  B_WatchHome
//
//  Created by dllo on 15/12/22.
//  Copyright © 2015年 DHF. All rights reserved.
//

#import "AppTools.h"


@implementation AppTools

+ (void)getDataWithURL:(NSString *)url Block:(AppToolsDataBlock)block
{
    //编码
    NSString *urlEncode = [url stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    
    
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/plain",@"text/json",@"application/json",@"text/javascript",@"text/html",nil];

    //缓存
    NSString *pathString = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) lastObject];
    
    NSString *pathLast = [NSString stringWithFormat:@"/Caches/WatchHome/%lu.text", (unsigned long) [url hash]];
    //创建字符串文件存储路径
    NSString *PathName = [pathString stringByAppendingString:pathLast];
    
//    NSLog(@"缓存路径：%@", PathName);
    
    [manager GET:urlEncode parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
//        [responseObject writeToFile:PathName atomically:YES encoding:NSUTF8StringEncoding error:nil];
        
        BOOL boo = [NSKeyedArchiver archiveRootObject:responseObject toFile:PathName];
        if (boo) {
            NSLog(@"成功缓存");
        }
        else
        {
            NSLog(@"失败");
        }
        
        if (responseObject) {
            block(responseObject);
        }
        else{
            NSLog(@"返回数据为空，请检查");
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        id result = [NSMutableDictionary dictionaryWithContentsOfFile:PathName];
        
        block(result);
        
    }];
    
    
}


@end
